<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" style="margin-bottom:15px">添加角色</el-button>
      <el-table :data="rolesList" stripe border>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="bd"
              :class="i==0?'bt':''"
              v-for="(item1,i) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="i==0?'':'bt'" v-for="(item2,i) in item1.children" :key="item2.id">
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      @close="removeRightById(scope.row,item2.id)"
                      closable
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-row v-for="item3 in item2.children" :key="item3.id">
                      <el-col>
                        <el-tag
                          type="warning"
                          @close="removeRightById(scope.row,item3.id)"
                          closable
                        >{{item2.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="400px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRight(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRight((scope.row))">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="showRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setRightVisible" @close="setRightClose" width="50%">
      <!-- tree -->
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        :props="treeProps"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户编辑 -->
     <el-dialog title="角色编辑" :visible.sync="setEditRightVisible" width="50%">
      <el-form ref="editRightRef" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" >
            <el-input v-model="roleDesc"></el-input>
          </el-form-item>
      </el-form>    
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="setEditRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="setEditRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //默认选中的节点值
      defKeys: [],
      //当前即将分配角色的id
      roleId: '',
     //角色编辑弹出框
     setEditRightVisible:false,
    //角色名，描述
    roleDesc:"",
    roleName:"",
    roleId:""
    }
  },

  methods: {
    //获取角色列表
    async getRoles() {
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status == 200) {
        this.rolesList = res.data
      }
      // console.log(this.rolesList)
    },
    // 根据id删除对应的权限
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        this.$message('删除取消')
      })
      // console.log(confirmResult)
      console.log(role, id)
      const { data: res } = await this.axios.delete(
        `roles/${role.id}/rights/${id}`
      )
      role.children = res.data
    },
    //设置分配权限
    async showRightDialog(role) {
      const { data: res } = await this.axios.get(`rights/tree`)
      // console.log(data)
      // console.log(res)
      this.roleId = role.id
      if (res.meta.status != 200) {
        return this.$message.err('获取数据失败')
      }
      // 把获取到的数据存储到rightsList中
      this.rightsList = res.data
      // console.log(this.rightsList)
      // console.log(role)
      this.getLeafkeys(role)
      this.setRightVisible = true
    },
    //通过递归的方式，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafkeys(node) {
      // 如果当前的node节点不包含children属性，则是三级节点
      
      node.children.forEach(item => {
        if(!item.children){
          return this.defKeys.push(item.id)
        }
        this.getLeafkeys(item)
        })
    },
    // 当关闭时候
    setRightClose() {
      this.defKeys = []
    },
    // 角色权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      console.log(idStr)
      const { data: res } = await this.axios.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoles()
      this.setRightVisible = false
    },
    //角色编辑
    editRight(role){
      // console.log(role)
      this.roleDesc = role.roleDesc
      this.roleName = role.roleName
      this.roleId = role.id
      this.setEditRightVisible=true;
    },
    //角色编辑弹出框确认修改时
    async setEditRight(){
      const {data:res} = await this.axios.put(`roles/${this.roleId}`,{roleName:this.roleName,roleDesc:this.roleDesc})
      console.log(res)
      if(res.meta.status !== 200){
        this.$message.error('修改失败')
      }
      this.setEditRightVisible=false;
      this.getRoles()
    },
    // 角色删除
    async deleteRight(role){
      const confirmResult = await this.$confirm(
            '此操作将永久删除该角色，是否继续',
            '提示',
            {
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type:'warning'
            }
        ).catch(err =>err)
      if(confirmResult == 'confirm'){
        const {data:res} = await this.axios.delete(`roles/${role.id}`)
          if(res.meta.status !== 200){
            this.$message.error("delete false")
          }else{
            this.$message.success('delete succeed')
            this.getRoles()
          }
        }else{
          this.$message.info('用户取消删除')
        }
      }
      
  },

  created() {
    this.getRoles()
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bt {
  border-top: 1px #eee solid;
}
.bd {
  border-bottom: 1px #eee solid;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
